package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.stream.CollectorUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 缓存 商铺类型
     * @return
     */
    @Override
    public Result queryShopTypeList() {

        // 1、先从 redis中查询
        List<String> shopTypeStrList = stringRedisTemplate.opsForList().range("ShopTypeList", 0, -1);
        List<ShopType> shopTypeList = new ArrayList<>();

        // 2、redis命中 返回
        if(CollectionUtil.isNotEmpty(shopTypeStrList)){
            shopTypeList = shopTypeStrList.stream().map(shopTypeStr ->{
                ShopType shopType = JSONUtil.toBean(shopTypeStr, ShopType.class);
                return shopType;
            }).collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }
        // 3、未命中 从 数据库中查询 写redis中
        shopTypeList = query().orderByAsc("sort").list();
        if(CollectionUtil.isEmpty(shopTypeList)){
            return Result.fail("店铺类型不存在");
        }
        // 3.1 把 得到的 ShopType bean 对象数组 系列化
        shopTypeStrList = shopTypeList.stream().map(
                shopType ->
                    JSONUtil.toJsonStr(shopType)
        ).collect(Collectors.toList());

        stringRedisTemplate.opsForList().leftPushAll("ShopTypelist",shopTypeStrList);
        // 4、返回店铺类型数据

        return Result.ok(shopTypeList);
    }
}
